"""
Case Type   : GUC参数--连接认证
Case Name   : gs_guc set修改参数listen_addresses为空,合理报错
              连接数据库
Create At   : 2021/04/02
Owner       : zhuanghuan96
Description :
    1、查看listen_addresses默认值；
    2、设置listen_addresses参数为空
    3、恢复默认值
Expect      :
    1、listen_addresses默认值为监听本机TCP/IP地址
    2、修改listen_addresses参数为空,重启数据库报错
    3、恢复默认值成功
History     :modified by zhuanghuan96，2023.03.21，参数listen_addresses不允许为空，
             修改用例
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node

LOGGER = Logger()
COMMONSH = CommonSH("PrimaryDbUser")


class GUC(unittest.TestCase):
    def setUp(self):
        LOGGER.info(
            '-Opengauss_Function_Guc_Connectionauthentication_Case0302start-')
        self.constant = Constant()
        self.user_node = Node("PrimaryDbUser")

    def test_listen_addresses(self):
        LOGGER.info(f'-----{os.path.basename(__file__)} start-----')
        sql_cmd = COMMONSH.execut_db_sql("show listen_addresses;")
        LOGGER.info(sql_cmd)
        self.default_value = sql_cmd.split("\n")[-2].strip()
        LOGGER.info("步骤1:设置listen_addresses参数为0.0.0.0并重启数据库;"
                    "重启数据库失败")
        sql_cmd = COMMONSH.execute_gsguc("set",
                                         self.constant.GSGUC_SUCCESS_MSG,
                                         "listen_addresses=''",
                                         node_name=f"{self.user_node}",
                                         single=True)
        LOGGER.info(sql_cmd)
        self.assertTrue(sql_cmd)
        sql_cmd = COMMONSH.restart_db_cluster()
        LOGGER.info(sql_cmd)
        status = COMMONSH.get_db_cluster_status()
        LOGGER.info(status)
        self.assertFalse("Normal" in status or "Degraded" in status)

    def tearDown(self):
        LOGGER.info("步骤2:恢复默认值")
        result = COMMONSH.execute_gsguc("set",
                                        self.constant.GSGUC_SUCCESS_MSG,
                                        f"listen_addresses="
                                        f"'{self.default_value}'",
                                        node_name=f"{self.user_node}",
                                        single=True)
        LOGGER.info(result)
        result = COMMONSH.restart_db_cluster()
        LOGGER.info(result)
        status = COMMONSH.get_db_cluster_status()
        self.assertTrue("Normal" in status or "Degraded" in status)
        LOGGER.info(f'-----{os.path.basename(__file__)} end-----')
